package ele_handler

import (
	"fmt"
	"go-yuque/logger"
	"golang.org/x/net/html"
	"path/filepath"
	"strings"
)

// card 元素 name="math"
func init() {
	registerInitFunc(func() YuqueElementHandler {
		return &cardMathHandlerStruct{
			BaseHandler: BaseHandler{
				elements: []string{"card"},
				attributes: map[string]string{
					"name": "math",
				},
			},
		}
	})
}

type cardMathHandlerStruct struct {
	BaseHandler
	Code      string `json:"code"` // 数学公式
	imageBase        // 数学公式生成图片地址
	Id        string `json:"id"`
}

func (m *cardMathHandlerStruct) doHandle() (err error) {
	err = parseCardJson(m.node, m)
	if err != nil {
		logger.Errorf("[cardMath]解析异常")
		sb := strings.Builder{}
		err = html.Render(&sb, m.node)
		if err != nil {
			m.WriteTextContext(sb.String())
		}
		return
	}

	if len(m.Code) > 0 {
		// 通过 ```math 来显示数学公式
		sbT := strings.Builder{}
		sbT.WriteString("```math\n")
		sbT.WriteString(m.Code)
		sbT.WriteString("```\n")

		m.WriteTextContext(sbT.String())
	} else if len(m.Src) > 0 {
		imageName := filepath.Base(m.Src)
		m.zoom = 100
		err = getImage(m.imageBase, imageName, m.downloadTocPath, m)
	} else {
		logger.Errorf("[cardMath]code为空")
		return fmt.Errorf("[cardMath]code为空")
	}

	return
}
